#设置各种参数
# typeset ORA_PRI_IP='@@ORA_PRI_IP@@'               #主服务器ip 10.27.5.199
# typeset ORA_SLA_IP='@@ORA_SLA_IP@@'               #从服务器ip 10.27.5.139
# typeset ORA_PRI_TNS_PORT='@@ORA_PRI_TNS_PORT@@' #1521
# typeset ORA_SLA_TNS_PORT='@@ORA_SLA_TNS_PORT@@' #1521
# typeset ORA_SLA_SSH_PORT='@@ORA_SLA_SSH_PORT@@' #22
# typeset ORA_PRI_HOST_USER='@@ORA_PRI_HOST_USER@@'                   #主服务器远程用户 oracle
# typeset ORA_PRI_HOST_PASSWD='@@ORA_PRI_HOST_PASSWD@@'           #主服务器远程密码 oracle
# typeset ORA_SLA_HOST_USER='@@ORA_SLA_HOST_USER@@'                   #从服务器远程用户 oracle
# typeset ORA_SLA_HOST_PASSWD='@@ORA_SLA_HOST_PASSWD@@'           #从服务器远程密码 oracle
# typeset check_times='@@check_times@@'                  #命令重复次数
# typeset ORA_PRI_SID='@@ORA_PRI_SID@@'                       #设置主库SID orcl
# typeset ORA_PRI_SID_UP=$(echo "${ORA_PRI_SID}" | tr '[a-z]' '[A-Z]') #ORCL
# typeset ORA_PRI_SID_DOWN=$(echo "${ORA_PRI_SID}" | tr '[A-Z]' '[a-z]') #ORCL
# typeset ORA_SLA_SID='@@ORA_SLA_SID@@'                       #设置从库SID orcl
# typeset ORA_PRI_DB_UNIQUE_NAME='@@ORA_PRI_DB_UNIQUE_NAME@@'            #设置主库uniqname orcl_pri
# typeset ORA_SLA_DB_UNIQUE_NAME='@@ORA_SLA_DB_UNIQUE_NAME@@'            #设置从库uniqname orcl_stl
# typeset ORA_PRI_SERVICE_NAME='@@ORA_PRI_SERVICE_NAME@@' #fsda.pri orcl_pri.pri
# typeset ORA_SLA_SERVICE_NAME='@@ORA_SLA_SERVICE_NAME@@' #orcl_stl.stl orcl_stl.pri
#ORACLE_OWNER=oracle
#ORACLE_SID=orcl
#ORACLE_HOSTNAME=pri
#ORACLE_BASE=/db/app/oracle
#ORACLE_HOME=${ORACLE_BASE}/product/11.2.0/db_1
#SPFILE_PATH=${ORACLE_HOME}/dbs
#ORA_NLS10=${ORACLE_HOME}/nls/data
#TNS_ADMIN=${ORACLE_HOME}/network/admin
# typeset ORA_PRI_IP='10.27.5.199'               #主服务器ip
# typeset check_times='5'                        #命令重复次数
# typeset ORA_PRI_SID='orcl'                       #设置主库SID orcl
# typeset ORA_SLA_DB_UNIQUE_NAME='orcl_stl02'    #主库db_unique_name
# typeset ORA_SLA_IP='10.27.3.134'               #备服务器ip
# typeset ORA_SLA_TNS_PORT='1521'                #备服务tns端口
# typeset ORA_SLA_SERVICE_NAME='orcl_stl02.pri'  #备服务servicename
# typeset ORA_SLA_SID='orcl'                     #备服务sid
# typeset ORA_SLA_HOST_USER='oracle'             #备服务远程oracle用户名
# typeset ORA_SLA_HOST_PASSWD='oracle'           #备服务远程oracle用户密码
# typeset ORA_SLA_SSH_PORT='22'                  #备服务ssh端口

### test begin ###
typeset ORA_PRI_IP='@@ORA_PRI_IP@@'               #主服务器ip
typeset check_times='@@check_times@@'                        #命令重复次数
typeset ORA_PRI_SID='@@ORA_PRI_SID@@'                       #设置主库SID orcl
typeset ORA_SLA_DB_UNIQUE_NAME='@@ORA_SLA_DB_UNIQUE_NAME@@'    #主库db_unique_name
typeset ORA_SLA_IP='@@ORA_SLA_IP@@'               #备服务器ip
typeset ORA_SLA_TNS_PORT='@@ORA_SLA_TNS_PORT@@'                #备服务tns端口
typeset ORA_SLA_SERVICE_NAME='@@ORA_SLA_SERVICE_NAME@@'  #备服务servicename
typeset ORA_SLA_SID='@@ORA_SLA_SID@@'                     #备服务sid
typeset ORA_SLA_HOST_USER='@@ORA_SLA_HOST_USER@@'             #备服务远程oracle用户名
typeset ORA_SLA_HOST_PASSWD='@@ORA_SLA_HOST_PASSWD@@'           #备服务远程oracle用户密码
typeset ORA_SLA_SSH_PORT='@@ORA_SLA_SSH_PORT@@'                  #备服务ssh端口
### test end ###

#配置日志路径
if [ -z "$ORA_PRI_IP" ];then
    $ORA_PRI_IP=$(/usr/sbin/ip a|grep `/usr/sbin/ip r|grep default|awk '{print $5}'`|grep inet|awk '{print $2}'|awk -F'/' '{print $1}')
fi
typeset SCRIPT_NAME="oracle_master_${ORA_PRI_IP}_${ORA_SLA_IP}"
typeset LOG_PATH='/tmp/dr_log'
[ ! -d "${LOG_PATH}" ] && mkdir -p ${LOG_PATH}
typeset LOG_FILE="${LOG_PATH}/${SCRIPT_NAME}.log"
[ ! -f "${LOG_FILE}" ] && touch ${LOG_FILE}

function log_format()
{
    echo "[`date +"%F %H:%M:%S"`] [$*]" | tee -a ${LOG_FILE}
}

log_format "begin to build oracle master................................."

#设置oracle环境变量
source ~/.bash_profile

#检查check次数
[ ! ${check_times} ] && typeset check_times='3'
expr 1 + ${check_times} &>/dev/null
if [ $? -ne 0 ];then
    log_format "ERROR" 'Argument needs to be integer' && log_format "ERROR" "script_execute_error!" && exit 1
fi

###############################################################################
#生成pfile文件并修改
initfilepath=${ORACLE_HOME}/dbs/init${ORA_PRI_SID}.ora
if [ -e "$initfilepath.`date +%F`_shellbak" ];then
    log_format "INFO" "$initfilepath.`date +%F`_shellbak exits "
else
    cp $initfilepath{,.`date +%F`_shellbak}
    if [ -e "$initfilepath.`date +%F`_shellbak" ];then
        log_format "INFO" "$initfilepath.`date +%F`_shellbak create success"
    else
        log_format "ERROR" "$initfilepath.`date +%F`_shellbak faile to create" && log_format "ERROR" "script_execute_error!" && exit 1
    fi
fi
sqlplus / as sysdba << EOFAA
create pfile from spfile;
EOFAA

cd $ORACLE_HOME/dbs

##检查或创建归档目录,有目录判断目录权限
if [ ! -d "${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog" ];then
  mkdir ${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog
  if [ $? -ne 0 ];then
    log_format "ERROR" "create dir ${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog failed."
    exit 10
  else
    log_format "INFO" "create dir ${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog succeed."
  fi
else
    touch ${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog/`date +%F`.test.txt
    if [ $? -eq 0 ];then
        rm -rf ${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog/`date +%F`.test.txt
        log_format "INFO" "${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog have write permission"
    else
        log_format 'ERROR' "${ORACLE_BASE}/oradata/${ORA_PRI_SID}/archivelog no write permission" && log_format "ERROR" "script_execute_error!" && exit 1
    fi
fi


#获取本机log_archive_dest的数字
if [ ! -e "$initfilepath" ] || [ ! $initfilepath ];then
    log_format "ERROR" "can not find pfile $initfilepath" && log_format "ERROR" "script_execute_error!" && exit 1
fi

cat $initfilepath|grep LOG_ARCHIVE_CONFIG|grep ${ORA_SLA_DB_UNIQUE_NAME}
if [ $? -ne 0 ];then
    localnum=0
    for i in `cat $initfilepath|grep "LOG_ARCHIVE_DEST_[0-9][0-9]*"|awk -F'=' '{print $1}'|awk -F'_' '{print $4}'|sed s'/=//'| sed -e 's/^[ ]*//g' | sed -e 's/[ ]*$//g'`
    do
        expr 1 + ${i} &>/dev/null
        if [ $? -ne 0 ];then
            log_format "ERROR" 'faile to get destnumber' && log_format "ERROR" "script_execute_error!" && exit 1
        fi
        if [ $i -gt $localnum ];then
            let localnum=i
        fi
    done
    let newnum=localnum+1

echo "LOG_ARCHIVE_DEST_$newnum=
 'SERVICE=${ORA_SLA_DB_UNIQUE_NAME} ASYNC
  VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE)
  DB_UNIQUE_NAME=${ORA_SLA_DB_UNIQUE_NAME}'
LOG_ARCHIVE_DEST_STATE_$newnum=ENABLE" >> init${ORA_PRI_SID}.ora
    old=`cat $initfilepath|grep LOG_ARCHIVE_CONFIG|awk -F')' '{print $1}'`
    new="$old,${ORA_SLA_DB_UNIQUE_NAME})'"
    sed -i /LOG_ARCHIVE_CONFIG/d $initfilepath
    echo $new >> $initfilepath
    log_format "INFO" "pfile has been changed"
else
  log_format "WARNNING" "${ORA_SLA_DB_UNIQUE_NAME} exits,do not modify pfile this time!"
fi

sqlplus / as sysdba << EOFAA
shutdown immediate;
create spfile from pfile;
startup;
EOFAA

cd $ORACLE_HOME/network/admin
#检查或备份tnsnames.ora
tnsnamepath=$ORACLE_HOME/network/admin/tnsnames.ora
if [ -e "$tnsnamepath.`date +%F`_shellbak" ];then
    log_format "INFO" "$tnsnamepath.`date +%F`_shellbak exits "
else
    cp $tnsnamepath{,.`date +%F`_shellbak}
    if [ -e "$tnsnamepath.`date +%F`_shellbak" ];then
        log_format "INFO" "$tnsnamepath.`date +%F`_shellbak create success"
    else
        log_format "ERROR" "$tnsnamepath.`date +%F`_shellbak faile to create" && log_format "ERROR" "script_execute_error!" && exit 1
    fi
fi

# ORA_PRI_DB_UNIQUE_NAME 可能大小写
# 备库监听配置
typeset sla_line_lst=($(grep -ni "^${ORA_SLA_DB_UNIQUE_NAME} " -A8 tnsnames.ora | grep -E 'HOST|SERVICE_NAME|(UR=A)' | sed 's/-//g' | awk '{print $1}'))
if [ -z "${sla_line_lst}" ]
then
  echo "${ORA_SLA_DB_UNIQUE_NAME} =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = ${ORA_SLA_IP})(PORT = ${ORA_SLA_TNS_PORT}))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = ${ORA_SLA_SERVICE_NAME})
      (UR=A)
    )
  )

" >> tnsnames.ora
else  
  sed -i "${sla_line_lst[0]}s/HOST =.*/HOST = ${ORA_SLA_IP})(PORT = ${ORA_SLA_TNS_PORT}))/g" tnsnames.ora
  sed -i "${sla_line_lst[1]}s/SERVICE_NAME =.*/SERVICE_NAME = ${ORA_SLA_SERVICE_NAME})/g" tnsnames.ora
  if [ ${#sla_line_lst[*]} -eq 2 ]
  then
    sed -i "${sla_line_lst[1]}a      (UR=A)" tnsnames.ora
  fi
fi


#拷贝文件
cd $ORACLE_HOME/dbs

if which expect
then
  log_format "INFO" "expect OK!"
else
  log_format "ERROR" "expect NOT found!"
  log_format "ERROR" "script_execute_error!" && exit 10
fi

#拷贝密码文件
expect << EOFXX
spawn scp -rp -P${ORA_SLA_SSH_PORT} orapw${ORA_PRI_SID} ${ORA_SLA_HOST_USER}@${ORA_SLA_IP}:$ORACLE_HOME/dbs/orapw${ORA_SLA_SID}

expect {
	"*password:*" {
		set timeout 1000
		send "${ORA_SLA_HOST_PASSWD}\r"
		exp_continue
		}
	"*es/no)?*" {
		send "yes\r"
		exp_continue
		}
	timeout {
		puts "connect is timeout"
		exit 3
		}
	}
EOFXX

#拷贝pfile参数文件
expect << EOFYY
spawn scp -rp -P${ORA_SLA_SSH_PORT} init${ORA_PRI_SID}.ora ${ORA_SLA_HOST_USER}@${ORA_SLA_IP}:$ORACLE_HOME/dbs/init${ORA_SLA_SID}.ora

expect {
	"*password:*" {
		set timeout 1000
		send "${ORA_SLA_HOST_PASSWD}\r"
		exp_continue
		}
	"*es/no)?*" {
		send "yes\r"
		exp_continue
		}
	timeout {
		puts "connect is timeout"
		exit 3
		}
	}
EOFYY

#拷贝tnsnames配置文件
expect << EOFZZ
spawn scp -rp -P${ORA_SLA_SSH_PORT} $ORACLE_HOME/network/admin/tnsnames.ora ${ORA_SLA_HOST_USER}@${ORA_SLA_IP}:$ORACLE_HOME/network/admin/tnsnames.ora

expect {
	"*password:*" {
		set timeout 1000
		send "${ORA_SLA_HOST_PASSWD}\r"
		exp_continue
		}
	"*es/no)?*" {
		send "yes\r"
		exp_continue
		}
	timeout {
		puts "connect is timeout"
		exit 3
		}
	}
EOFZZ

lsnrctl stop
if [ $? -ne 0 ];then
    log_format "ERROR" "lsnrctl stop failed." && log_format "ERROR" "script_execute_error!" && exit 1
else
    log_format "INFO" "lsnrctl stop successfully."
fi

lsnrctl start
if [ $? -ne 0 ];then
    log_format "ERROR" "lsnrctl start failed." && log_format "ERROR" "script_execute_error!" && exit 1
else
    log_format "INFO" "lsnrctl start successfully."
fi

MAIN_RET=$?
log_format "INFO" "MAIN_RET=${MAIN_RET}"

if [[ "$MAIN_RET" == 0 ]]
then
    log_format "INFO" "script_execute_success!"
else
    log_format "ERROR" "script_execute_error!"
fi

exit $MAIN_RET